<template>
  <view class="album-detail-container">
    <scroll-view scroll-y class="content-scroll" @refresherrefresh="onRefresh" :refresher-enabled="true" :refresher-triggered="isRefreshing">
      <!-- Header Section -->
      <view class="album-header" v-if="currentAlbum">
        <image class="header-bg" :src="safeImageUrl(currentAlbum.coverUrl, 'album')" mode="aspectFill"></image>
        <view class="header-overlay"></view>
        <view class="header-content">
          <text class="album-name">{{ currentAlbum.name }}</text>
          <text class="album-description">{{ currentAlbum.description || '暂无描述' }}</text>
          <text class="photo-count">{{ photos.length }} 张照片</text>
        </view>
      </view>

      <!-- Action Bar -->
      <view class="action-bar">
        <button class="action-btn upload-btn" @click="handleUpload">
          <text class="icon">+</text> 上传照片
        </button>
        <button class="action-btn cover-btn" @click="handleChangeCover">
          更换封面
        </button>
        <button class="action-btn delete-btn" @click="handleDeleteAlbum">
          删除相册
        </button>
      </view>

      <!-- Photo Grid -->
      <view class="photo-grid" :class="getGridClass()" v-if="photos.length > 0">
        <view class="photo-item" :class="getPhotoItemClass()" v-for="(photo, index) in photos" :key="photo.id">
          <image class="photo-image" :src="safeImageUrl(photo.fileUrl, 'photo')" mode="aspectFill" @click="previewImage(index)"></image>
          
          <!-- 删除按钮 -->
          <view class="delete-btn" @click.stop="handleDeletePhoto(photo)">
            <text class="delete-icon">×</text>
          </view>
          
          <!-- 照片信息 -->
          <view class="photo-info" v-if="photo.uploader">
            <text class="uploader-name">{{ photo.uploader.nickname || photo.uploader.username }}</text>
          </view>
        </view>
      </view>

      <!-- Empty State -->
      <view class="empty-state" v-if="photos.length === 0 && !loading">
        <image class="empty-icon" :src="imageHelper.getDefaultAlbum()" mode="aspectFit" />
        <text class="empty-text">相册里还没有照片</text>
        <button class="upload-first-btn" @click="handleUpload">上传第一张照片</button>
      </view>
    </scroll-view>

    <!-- Loading State -->
    <view class="loading-state" v-if="loading && !isRefreshing">
      <uni-load-more status="loading"></uni-load-more>
    </view>
  </view>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import imageHelper from '@/utils/imageHelper';
import config from '@/utils/config.js';
import { uploadFile } from '@/utils/request';

export default {
  data() {
    return {
      albumId: null,
      loading: false,
      isRefreshing: false,
      imageHelper
    };
  },
  computed: {
    ...mapState('album', ['photos', 'currentAlbum']),
  },
  onLoad(options) {
    const albumId = options ? parseInt(options.albumId) : null;
    if (albumId && !isNaN(albumId)) {
      this.albumId = albumId;
      this.loadPageData();
    } else {
      uni.showToast({ title: '相册ID无效', icon: 'none' });
      uni.navigateBack();
    }
  },
  methods: {
    ...mapActions('album', ['fetchPhotos', 'uploadPhoto', 'fetchAlbumDetails', 'deleteAlbum', 'deletePhoto', 'updateAlbumCover']),

    getGridClass() {
      const photoCount = this.photos.length;
      if (photoCount <= 2) {
        return 'few-photos';
      } else {
        return 'many-photos';
      }
    },

    getPhotoItemClass() {
      const photoCount = this.photos.length;
      if (photoCount === 1) {
        return 'single-photo';
      } else if (photoCount === 2) {
        return 'two-photos';
      } else {
        return 'three-or-more';
      }
    },

    async loadPageData() {
      if (this.loading) return;
      this.loading = true;
      try {
        await Promise.all([
          this.fetchAlbumDetails(this.albumId),
          this.fetchPhotos(this.albumId)
        ]);
        console.log('相册详情:', this.currentAlbum);
        console.log('照片列表:', this.photos);
        console.log('照片数量:', this.photos.length);
        
        // 显示每张照片的详细信息
        this.photos.forEach((photo, index) => {
          console.log(`照片${index + 1}:`, {
            id: photo.id,
            fileUrl: photo.fileUrl,
            uploader: photo.uploader,
            albumId: photo.albumId,
            isDeleted: photo.isDeleted
          });
        });
      } catch (error) {
        console.error('加载失败:', error);
        uni.showToast({ title: '加载失败', icon: 'none' });
      } finally {
        this.loading = false;
      }
    },
    
    async onRefresh() {
      if (this.isRefreshing) return;
      this.isRefreshing = true;
      try {
        await Promise.all([
          this.fetchAlbumDetails(this.albumId),
          this.fetchPhotos(this.albumId)
        ]);
      } catch (error) {
        // Handle error silently as toast is shown in loadPageData
      } finally {
        this.isRefreshing = false;
      }
    },

    safeImageUrl(url, type) {
      console.log('处理图片URL:', url, 'type:', type);
      if (!url) {
        console.log('URL为空，返回默认图片');
        return type === 'album' ? imageHelper.getDefaultAlbum() : imageHelper.getDefaultAvatar();
      }
      if (url.startsWith('http')) {
        console.log('URL是完整HTTP地址:', url);
        return url;
      }
      const finalUrl = imageHelper.safeImageUrl(url);
      console.log('构建的最终URL:', finalUrl);
      return finalUrl;
    },

    previewImage(index) {
      const urls = this.photos.map(p => this.safeImageUrl(p.fileUrl, 'photo'));
      uni.previewImage({
        urls: urls,
        current: index
      });
    },

    handleUpload() {
      uni.chooseImage({
        count: 9,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: async (res) => {
          uni.showLoading({ title: '上传中...' });
          try {
            for (const tempFilePath of res.tempFilePaths) {
              await this.uploadPhoto({ albumId: this.albumId, filePath: tempFilePath });
            }
            uni.hideLoading();
            uni.showToast({ title: '上传成功', icon: 'success' });
            this.fetchPhotos(this.albumId); // Refresh photo list
          } catch (error) {
            uni.hideLoading();
            uni.showToast({ title: '上传失败', icon: 'none' });
          }
        }
      });
    },

    async handleDeleteAlbum() {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这个相册吗？此操作不可撤销。',
        success: async (res) => {
          if (res.confirm) {
            uni.showLoading({ title: '删除中...' });
            try {
              await this.deleteAlbum(this.albumId);
              uni.hideLoading();
              uni.showToast({
                title: '删除成功',
                icon: 'success'
              });
              setTimeout(() => {
                uni.navigateBack();
              }, 1500);
            } catch (error) {
              uni.hideLoading();
              uni.showToast({
                title: '删除失败',
                icon: 'none'
              });
            }
          }
        }
      });
    },

    async handleDeletePhoto(photo) {
      console.log('准备删除照片:', photo);
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这张照片吗？',
        success: async (res) => {
          if (res.confirm) {
            console.log('用户确认删除，照片ID:', photo.id);
            uni.showLoading({ title: '删除中...' });
            try {
              await this.deletePhoto(photo.id);
              console.log('删除成功');
              uni.hideLoading();
              uni.showToast({
                title: '删除成功',
                icon: 'success'
              });
            } catch (error) {
              console.error('删除失败:', error);
              uni.hideLoading();
              uni.showToast({
                title: '删除失败: ' + (error.message || '未知错误'),
                icon: 'none'
              });
            }
          }
        }
      });
    },

    handleChangeCover() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: async (res) => {
          const tempFilePath = res.tempFilePaths[0];
          uni.showLoading({ title: '上传封面中...' });
          
          try {
            // 使用统一的上传方法
            const response = await uploadFile({
              url: '/file/upload',
              filePath: tempFilePath,
              name: 'file'
            });

            if (response.code === 200) {
              const coverUrl = response.data;
              
              // 更新相册封面
              await this.updateAlbumCover({
                albumId: this.albumId,
                coverUrl: coverUrl
              });
              
              uni.hideLoading();
              uni.showToast({
                title: '封面更新成功',
                icon: 'success'
              });
            } else {
              uni.hideLoading();
              uni.showToast({
                title: response.message || '封面上传失败',
                icon: 'none'
              });
            }
          } catch (error) {
            console.error('封面上传失败:', error);
            uni.hideLoading();
            uni.showToast({
              title: '封面上传失败',
              icon: 'none'
            });
          }
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.album-detail-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #fff;
}

.content-scroll {
  flex: 1;
  height: 100%;
}

.album-header {
  position: relative;
  height: 400rpx;
  color: white;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  padding: 40rpx;
  
  .header-bg {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 1;
  }

  .header-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(to top, rgba(0,0,0,0.6) 0%, rgba(0,0,0,0) 100%);
    z-index: 2;
  }

  .header-content {
    position: relative;
    z-index: 3;
    
    .album-name {
      font-size: 48rpx;
      font-weight: bold;
      display: block;
      margin-bottom: 8rpx;
    }
    
    .album-description {
      font-size: 28rpx;
      opacity: 0.9;
      margin-bottom: 12rpx;
    }
    
    .photo-count {
      font-size: 24rpx;
      opacity: 0.8;
    }
  }
}

.action-bar {
  display: flex;
  justify-content: space-around;
  padding: 30rpx;
  background: #fff;
  border-bottom: 1px solid #f0f0f0;
  
  .action-btn {
    flex: 1;
    margin: 0 10rpx;
    padding: 20rpx;
    border: none;
    border-radius: 16rpx;
    font-size: 28rpx;
    font-weight: 500;
    
    &.upload-btn {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: #fff;
      
      .icon {
        font-size: 32rpx;
        margin-right: 8rpx;
      }
    }
    
    &.cover-btn {
      background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
      color: #fff;
    }
    
    &.delete-btn {
      background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
      color: #fff;
    }
  }
}

.photo-grid {
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  padding: 12rpx;
  align-items: flex-start;
  
  /* 当照片数量较少时，居中显示 */
  &.few-photos {
    justify-content: center;
  }
  
  /* 当照片数量较多时，从左开始排列 */
  &.many-photos {
    justify-content: flex-start;
  }
}

.photo-item {
  position: relative;
  border-radius: 12rpx;
  overflow: hidden;
  background: #f8f8f8;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.1);
  margin: 8rpx;
  
  /* 根据照片数量动态调整宽度 */
  &.single-photo {
    width: 300rpx;
    height: 300rpx;
    flex-shrink: 0;
  }
  
  &.two-photos {
    width: calc(50% - 16rpx);
    aspect-ratio: 1;
    flex-shrink: 0;
  }
  
  &.three-or-more {
    width: calc(33.33% - 16rpx);
    aspect-ratio: 1;
    flex-shrink: 0;
  }
  
  .photo-image {
    width: 100%;
    height: 100%;
    border-radius: 12rpx;
  }
  
  .delete-btn {
    position: absolute;
    top: 8rpx;
    right: 8rpx;
    width: 48rpx;
    height: 48rpx;
    background: rgba(255, 59, 48, 0.9);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    backdrop-filter: blur(10rpx);
    z-index: 10;
    
    .delete-icon {
      color: #fff;
      font-size: 32rpx;
      font-weight: bold;
      line-height: 1;
    }
  }
  
  .photo-info {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    background: linear-gradient(to top, rgba(0,0,0,0.7) 0%, rgba(0,0,0,0) 100%);
    padding: 24rpx 12rpx 8rpx;
    
    .uploader-name {
      color: #fff;
      font-size: 24rpx;
      text-shadow: 0 1rpx 2rpx rgba(0,0,0,0.5);
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 40rpx;
  
  .empty-icon {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 40rpx;
  }
  
  .empty-text {
    font-size: 28rpx;
    color: #999;
    margin-bottom: 40rpx;
  }
  
  .upload-first-btn {
    background: #007AFF;
    color: white;
    padding: 20rpx 60rpx;
    border-radius: 40rpx;
    font-size: 32rpx;
  }
}

.loading-state {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style> 